/**
 * 获取cookie
 */
function getCookie(name: string): string {
    let arr: RegExpMatchArray;
    const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`);
    const temp = document.cookie.match(reg);
    if (temp !== null && temp !== undefined) {
        arr = temp;
        return decodeURIComponent(arr[2]);
    }
    return '';
}

/**
 * 存cookie
 */
function setCookie(name: string, value: string, expiresDate = 24) {
    const date = new Date(); // 获取当前时间
    date.setTime(date.getTime() + expiresDate * 3600 * 1000); // 格式化为cookie识别的时间
    document.cookie = `${name}=${value};expires=${date.toUTCString()}`;
}

/**
 * 删除cookie
 */
function deleteCookie(name: string) {
    setCookie(name, '', -1);
}

function formatDate(date: any, fmt: any) {
    const dates = new Date(date);
    const o = {
        'y+': dates.getFullYear(),
        'M+': dates.getMonth() + 1, // 月份
        'd+': dates.getDate(), // 日
        'h+': dates.getHours(), // 小时
        'm+': dates.getMinutes(), // 分
        's+': dates.getSeconds(), // 秒
        'q+': Math.floor((dates.getMonth() + 3) / 3), // 季度
        S: dates.getMilliseconds(), // 毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, `${dates.getFullYear()}`.substr(4 - RegExp.$1.length));
    Object.keys(o).forEach((k) => {
        if (new RegExp(`(${k})`).test(fmt)) {
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length));
        }
    });
    return fmt;
}

function formatDateBeiJing(dates: any, fmt: any, name: any) {
    const date = new Date(dates);
    const timestampUtc = date.getTime() / 1000;
    const timestamp: any = name === 'UCT' ? timestampUtc : timestampUtc + 8 * 60 * 60;
    return formatDate(new Date(parseInt(timestamp, 10) * 1000), fmt);
}

let timeout: any = null;
function debounce(fn: any, wait: any) {
    if (timeout !== null) clearTimeout(timeout);
    timeout = setTimeout(fn, wait);
}
export { setCookie, getCookie, deleteCookie, formatDateBeiJing, debounce };
